import createAction from "./createAction";
import createReducer from "./createReducer";

/**
 *
 * 传入一个对象，内部循环生成对应的  reducer, actions, 再组成一个对象返回
 *
 *
 * createSlice函数允许我们提供一个带有reducer函数的对象
 * 并且它将根据我们列出的reducer的名称自动生成action type字符串和action creator函数
 * createSlice会返回一个分片的对象，包括了生成的reducer函数，以及reducer名称，以及actions对象上的actionCreators
 */
function createSlice(options) {
  const {
    name, // 切片名
    initialState = {}, // 初始状态
    reducers = {}, // 同步 reducers 处理函数
    extraReducers = {}, // 异步 reducers 处理函数
  } = options;
  // 函数前缀 1.
  const prefixedReducers = {};
  // actionCreator 对象 1.
  const actions = {};

  Object.keys(reducers).forEach((key) => {
    const type = `${name}/${key}`;

    // 函数前缀 2. 循环生成

    //prefixedReducers['counter1/add']=reducer;
    prefixedReducers[type] = reducers[key];

    // actionCreator 对象 2. 循环生成
    //actions.add = ()=>({type:'counter1/add'})
    actions[key] = createAction(type);
  });
  const reducer = createReducer(initialState, prefixedReducers, extraReducers);
  return {
    name,
    reducerPath: name,
    reducer,
    actions,
  };
}
export default createSlice;
